﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using zTalk.Network;

namespace zTalk
{
    public partial class AddFriend : Window
    {
        public AddFriend()
        {
            InitializeComponent();

            App.Handler.AddFriend += new PacketEventHandler(Handler_AddFriend);
            friendToAdd = true;
        }

        private bool friendToAdd;

        void Handler_AddFriend(object sender, PacketEventArgs ea)
        {
            if (ea.Result != null)
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                    if (friendToAdd == true)
                    {
                        Contacts w = (Contacts)App.Current.Windows[0];
                        w.UserItems.Add(ea.Result as UserItem);
                        friendToAdd = false;
                        Close();
                    }
                }));
            }
            else
            {
                triggerLoading(false);
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                    lblErrors.Content = "! Username does not exist";
                    errorPane.Visibility = Visibility.Visible;
                }));
            }
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                triggerLoading(true);

                Contacts w = (Contacts)App.Current.Windows[0];
                var x = (from u in w.UserItems
                         where u.Username == txtFriend.Text
                         select u).Single();
                lblErrors.Content = "! Username already in your friends list";
                errorPane.Visibility = Visibility.Visible;

                return;
            }
            catch (Exception) {}

            try
            {
                Packet packet = Packet.Create(
                    Opcodes.ADD_FRIEND,
                    Json.Encode<string[]>(new string[] { txtFriend.Text })
                );
                App.Client.SendPacket(packet);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void triggerLoading(bool start)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                btnOk.Content = (start == true) ? "Processing" : "Add";
                btnOk.IsEnabled = (start != true);
            }));
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtFriend.Focus();
        }
    }
}
